using System.Text.Json;
using WebAppDbTest.Models;

namespace WebAppDbTest.Services;

/// <summary>
/// AppLogs服务接口规范定义
/// </summary>
public interface IAppLogsServices
{
    /// <summary>
    /// 写入日志信息
    /// </summary>
    /// <param name="logs"></param>
    /// <param name="logLevel"></param>
    /// <returns></returns>
    Task WriteLogAsync(AppLogs logs, LogLevel logLevel = LogLevel.Information);

    /// <summary>
    /// 模型数据序列化json字符串
    /// </summary>
    /// <typeparam name="TData"></typeparam>
    /// <param name="data"></param>
    /// <returns></returns>
    Task<string> JsonSerializeAsync<TData>(TData data);
}

/// <summary>
/// AppLogs服务接口规范实现
/// </summary>
public class AppLogsServices : IAppLogsServices
{
    #region 构造函数 DI
    private readonly ILogger<AppLogsServices> _logger;

    public AppLogsServices(ILogger<AppLogsServices> logger)
    {
        _logger = logger;
    }
    #endregion

    /// <summary>
    /// 写入日志信息
    /// </summary>
    /// <param name="logs"></param>
    /// <param name="logLevel"></param>
    /// <returns></returns>
    public async Task WriteLogAsync(AppLogs logs, LogLevel logLevel = LogLevel.Information)
    {
        logs.LogLevel = logLevel;
        string jsonLogs = await JsonSerializeAsync(logs);

        switch (logLevel)
        {
            case LogLevel.Trace:
                _logger.LogTrace(jsonLogs);
                break;
            case LogLevel.Debug:
                _logger.LogDebug(jsonLogs);
                break;
            case LogLevel.Information:
                _logger.LogInformation(jsonLogs);
                break;
            case LogLevel.Warning:
                _logger.LogWarning(jsonLogs);
                break;
            case LogLevel.Error:
                _logger.LogError(jsonLogs);
                break;
            case LogLevel.Critical:
                _logger.LogCritical(jsonLogs);
                break;
            case LogLevel.None:
                _logger.LogInformation(jsonLogs);
                break;
            default:
                _logger.LogInformation(jsonLogs);
                break;
        }
    }

    /// <summary>
    /// json 序列化
    /// </summary>
    /// <typeparam name="TData"></typeparam>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<string> JsonSerializeAsync<TData>(TData data)
    {
        var options = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };
        await using var stream = new MemoryStream();
        await JsonSerializer.SerializeAsync(stream, data, options);
        stream.Position = 0;
        using var reader = new StreamReader(stream);
        return await reader.ReadToEndAsync();
    }
}